package br.com.vagacerta.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import br.com.vagacerta.modelo.Usuario;

@Repository
public class UsuarioDAO {

	private Connection connection;
	
	@Autowired
	public UsuarioDAO(DataSource dataSource) {
		try {
			this.connection = dataSource.getConnection();
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}
	}

	public Usuario getUsuario(Usuario usuario) {

		try {
			String sql = "select * from seg_usuario where login = ? and password = ? and status_ativo = 1 order by cod_usuario asc limit 1";
			Usuario user = new Usuario();
			PreparedStatement stmt = connection.prepareStatement(sql);
			stmt.setString(1, usuario.getLogin());
			stmt.setString(2, usuario.getPassword());
			ResultSet rs = stmt.executeQuery();

			while (rs.next()) {

				user.setCodUsuario(rs.getInt("COD_USUARIO"));
				user.setLogin(rs.getString("LOGIN"));
				user.setPassword(rs.getString("PASSWORD"));
				user.setPerfilUsuario(rs.getInt("COD_PERFIL_USUARIO"));
				user.setNomeCompleto(rs.getString("NOME_COMPLETO"));
				user.setStatusAtivo(rs.getByte("STATUS_ATIVO"));

			}

			rs.close();
			stmt.close();
			return user;
		} catch (SQLException e) {
			throw new RuntimeException(e);
		}

	}
}